package com.haotunet.app.goldtreasure.views;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.UnderlineSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.haotunet.app.goldtreasure.R;
import com.haotunet.app.goldtreasure.activity.MyWalletActivity;
import com.haotunet.app.goldtreasure.activity.RechargeFStebActivity;
import com.haotunet.app.goldtreasure.model.BaseModel;
import com.haotunet.app.goldtreasure.model.CardInfo;
import com.haotunet.app.goldtreasure.model.CardModel;
import com.haotunet.app.goldtreasure.model.OrderInfo;
import com.haotunet.app.goldtreasure.model.WalletInfo;
import com.haotunet.app.goldtreasure.net.ActionUtil;
import com.haotunet.app.goldtreasure.other.Interface.OnPassBackListener;
import com.haotunet.app.goldtreasure.utils.ActivityUtils;
import com.haotunet.app.goldtreasure.utils.ShareStore;
import com.haotunet.app.goldtreasure.utils.Strs;
import com.haotunet.app.goldtreasure.utils.UIHelper;
import com.haotunet.app.goldtreasure.views.PayPasswordView.OnPayListener;

public class OrderPopupView extends PopupWindow implements OnClickListener {
    private Activity mcontext;
    private LayoutInflater mLayoutInflater;
    private View rootView;
    private TextView popupTitle;
    private RelativeLayout rlBalance;
    private RelativeLayout rlCard;
    private TextView mTailNum, mLimit;
    private ImageView ivBack;
    private ImageView ivBankLogo;
    private ImageView ivBalance;
    private ImageView ivBalanceSelect, ivCardSelect;
    private TextView tvBalance;
    private TextView tvPayExcess;
    private TextView tvBankMainTain;
    private String mPayAmount;
    private Button btnPay;
    private RelativeLayout rlError;
    private boolean isBalancePay = false;
    private ShareStore shareStore;
    private OrderInfo orderInfo;
    private String mType;
    private DialogWidget mDialogWidget;
    private PayPasswordView passwordView;
    private String orderPrice;
    private CardInfo cardInfo;
    private WalletInfo walletInfo;
    private int time = 1;
    private Handler handle = new Handler() {

        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0:
                    checkOrderStatus();
                    break;
                default:
                    break;
            }
        }

    };

    public OrderPopupView(Activity context, String payAmount, String type, OrderInfo info) {
        this.mcontext = context;
        this.mPayAmount = payAmount;
        this.mType = type;
        this.orderInfo = info;
        shareStore = new ShareStore(context);
        mLayoutInflater = (LayoutInflater) mcontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        initViews();
        initData();

    }

    @SuppressWarnings("deprecation")
    private void initViews() {
        if (mType.equals("1")) {
            orderPrice = orderInfo.getCurrentOrderPrice();
        } else if (mType.equals("2")) {
            orderPrice = orderInfo.getPayment();
        } else if (mType.equals("3")) {
            orderPrice = orderInfo.getFee();
        } else if (mType.equals("4")) {
            orderPrice = orderInfo.getPayment();
        }
        rootView = mLayoutInflater.inflate(R.layout.popup_view_order, null);
        setContentView(rootView);
        popupTitle = (TextView) rootView.findViewById(R.id.popup_title);
        popupTitle.setText("付款" + mPayAmount + "元");
        ivBack = (ImageView) rootView.findViewById(R.id.iv_back);
        ivBankLogo = (ImageView) rootView.findViewById(R.id.iv_bank_logo);
        rlBalance = (RelativeLayout) rootView.findViewById(R.id.balance_layout);
        rlCard = (RelativeLayout) rootView.findViewById(R.id.card_layout);
        mLimit = (TextView) rootView.findViewById(R.id.available_line);
        mTailNum = (TextView) rootView.findViewById(R.id.tv_card);
        ivBalanceSelect = (ImageView) rootView.findViewById(R.id.iv_balance_selected);
        ivCardSelect = (ImageView) rootView.findViewById(R.id.iv_card_selected);
        tvBalance = (TextView) rootView.findViewById(R.id.tv_balance);
        tvPayExcess = (TextView) rootView.findViewById(R.id.txt_pay_excess);
        tvBankMainTain = (TextView) rootView.findViewById(R.id.txt_bank_maintain);
        ivBalance = (ImageView) rootView.findViewById(R.id.iv_balance);
        rlError = (RelativeLayout) rootView.findViewById(R.id.error_layout);
        btnPay = (Button) rootView.findViewById(R.id.btn_pay);
        setFocusable(true);
        setWidth(ViewGroup.LayoutParams.FILL_PARENT);
        setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
      /*  int color = mcontext.getResources().getColor(R.color.popup_root_view_bg);
        ColorDrawable colorDrawable = new ColorDrawable(color);
        setBackgroundDrawable(colorDrawable);*/
        if (mType.equals("2")) {
            rlBalance.setVisibility(View.GONE);
        }
        rlBalance.setOnClickListener(this);
        tvPayExcess.setOnClickListener(this);
        rlCard.setOnClickListener(this);
        ivBack.setOnClickListener(this);
        btnPay.setOnClickListener(this);
    }

    private void initData() {
        getBalance();
    }

    private void getBankInfo() {
        ActionUtil actionUtil = new ActionUtil(mcontext);
        actionUtil.getMyBankCardList();
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                CardModel cardModel = (CardModel) model;
                if (cardModel == null) {
                    UIHelper.showToast(mcontext, mcontext.getString(R.string.rank_fail));
                    return;
                }
                if (cardModel.getErrorMsg() != null) {
                    UIHelper.showToast(mcontext, cardModel.getErrorMsg());
                } else {
                    if (cardModel.getBankCards().size() > 0) {
                        cardInfo = cardModel.getBankCards().get(0);
                        Glide.with(mcontext).load(cardInfo.getBankCardLogo()).into(ivBankLogo);
                        mTailNum.setText(cardInfo.getBankName() + "(" + cardInfo.getBankCardlast4() + ")");
                        mLimit.setText(cardInfo.getPayLimits());
                        if (Double.parseDouble(mPayAmount) > Double.parseDouble(walletInfo.getBalanceWithdrawn()) && (Double.parseDouble(mPayAmount) > Double.parseDouble(cardInfo.getPayLimitation()) || "1".equals(cardInfo.getStatusType()))) {
                            btnPay.setEnabled(false);
                            btnPay.setBackground(mcontext.getResources().getDrawable(R.drawable.login_btn_bg_unclick));
                            rlError.setVisibility(View.VISIBLE);
                            showBankFailReason();
                            rlCard.setEnabled(false);
                            ivCardSelect.setSelected(false);
                            mTailNum.setSelected(false);
                        } else {
                            btnPay.setEnabled(true);
                            btnPay.setBackground(mcontext.getResources().getDrawable(R.drawable.login_btn_bg));
                            if ("1".equals(cardInfo.getStatusType())) {
                                mLimit.setText(cardInfo.getMaintainTime());
                            }
                            if (Double.parseDouble(mPayAmount) > Double.parseDouble(cardInfo.getPayLimitation()) || "1".equals(cardInfo.getStatusType())) {
                                rlCard.setEnabled(false);
                                ivCardSelect.setSelected(false);
                                mTailNum.setSelected(false);
                                balancePay();
                                setRechargeCannotPayView();
                            } else {
                                rlCard.setEnabled(true);
                                ivCardSelect.setSelected(true);
                                mTailNum.setSelected(true);
                            }
                        }
                    }
                }
            }
        });
    }

    private void setRechargeCannotPayView() {
        if ("2".equals(mType)) {
            btnPay.setEnabled(false);
            btnPay.setBackground(mcontext.getResources().getDrawable(R.drawable.login_btn_bg_unclick));
            rlError.setVisibility(View.VISIBLE);
            if (Double.parseDouble(mPayAmount) > Double.parseDouble(cardInfo.getPayLimitation())) {
                tvPayExcess.setText("您的银行卡超过限额，无法完成充值");
                tvPayExcess.setVisibility(View.VISIBLE);
            } else if ("1".equals(cardInfo.getStatusType())) {
                tvBankMainTain.setText("您的银行卡正在维护中");
                tvBankMainTain.setVisibility(View.VISIBLE);
            } else if (Double.parseDouble(mPayAmount) > Double.parseDouble(cardInfo.getPayLimitation()) && "1".equals(cardInfo.getStatusType())) {
                tvBankMainTain.setText("您的银行卡正在维护中");
                tvBankMainTain.setVisibility(View.VISIBLE);
            }
        }
    }

    private void showBankFailReason() {
        if ("1".equals(cardInfo.getStatusType())) {
            showBankMaintainTimeTip();
        } else if (Double.parseDouble(mPayAmount) > Double.parseDouble(cardInfo.getPayLimitation())) {
            showPayExcessTip();
        } else if ("1".equals(cardInfo.getStatusType()) && Double.parseDouble(mPayAmount) > Double.parseDouble(cardInfo.getPayLimitation())) {
            showBankMaintainTimeTip();
        }
    }

    private void showPayExcessTip() {
        if ("2".equals(mType)) {
            tvPayExcess.setText("您的银行卡超过限额，无法完成充值");
        } else {
            SpannableStringBuilder style = new SpannableStringBuilder(tvPayExcess.getText());
            style.setSpan(new RelativeSizeSpan(1f), 0, tvPayExcess.getText().length() - 5, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            style.setSpan(new RelativeSizeSpan(1.2f), tvPayExcess.getText().length() - 5, tvPayExcess.getText().length(),
                    Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            style.setSpan(new ForegroundColorSpan(mcontext.getResources().getColor(R.color.color_red)), tvPayExcess.getText().length() - 5, tvPayExcess.getText().length(),
                    Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            style.setSpan(new UnderlineSpan(), tvPayExcess.getText().length() - 5, tvPayExcess.getText().length(),
                    Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            tvPayExcess.setText(style);
        }
        tvPayExcess.setVisibility(View.VISIBLE);
    }

    private void showBankMaintainTimeTip() {
        mLimit.setText(cardInfo.getMaintainTime());
        tvBankMainTain.setVisibility(View.VISIBLE);
        if ("2".equals(mType)) {
            tvBankMainTain.setText("您的银行卡正在维护中");
        }
    }

    private void getBalance() {
        ActionUtil actionUtil = new ActionUtil(mcontext);
        actionUtil.getWalletPageInfo();
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                walletInfo = (WalletInfo) model;
                if (walletInfo == null) {
                    UIHelper.showToast(mcontext, mcontext.getString(R.string.rank_fail));
                    return;
                }
                if (walletInfo.getErrorMsg() != null) {
                    if (walletInfo.getErrorCode().equals(Strs.EXTRUSION_SIGN_IN)) {
                        ActivityUtils.forceQuit(mcontext, mcontext.getString(R.string.crowding_in_tips_txt));
                    } else {
                        UIHelper.showToast(mcontext, walletInfo.getErrorMsg());
                    }
                } else {
                    getBankInfo();
                    tvBalance.setText("账户余额(" + walletInfo.getBalanceWithdrawn() + ")元");
                    if (Double.parseDouble(mPayAmount) > Double.parseDouble(walletInfo.getBalanceWithdrawn())) {
                        tvBalance.setSelected(false);
                        ivBalance.setSelected(false);
                        rlBalance.setEnabled(false);
                    } else {
                        tvBalance.setSelected(true);
                        ivBalance.setSelected(true);
                    }
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                dismiss();
                break;
            case R.id.txt_pay_excess:
                ActivityUtils.gotoRecharge(mcontext);
                dismiss();
                break;
            case R.id.balance_layout:
                balancePay();
                break;
            case R.id.card_layout:
                cardPay();
                break;
            case R.id.btn_pay:
                mDialogWidget = new DialogWidget(mcontext, getDecorViewDialog());
                mDialogWidget.show();
                ActivityUtils.backgroundAlpha(mcontext, 1f);
                break;
            default:
                break;
        }
    }

    private void cardPay() {
        isBalancePay = false;
        ivCardSelect.setSelected(true);
        ivBalanceSelect.setSelected(false);
    }

    private void balancePay() {
        isBalancePay = true;
        ivBalanceSelect.setSelected(true);
        ivCardSelect.setSelected(false);
    }

    protected View getDecorViewDialog() {
        if (isBalancePay) {
            if (shareStore.getInt(Strs.IS_HAD_TRADING_PWD, 0) == 1) {
                passwordView = new PayPasswordView(2, 1, mcontext, null, "", null);
            } else {
                passwordView = new PayPasswordView(1, 1, mcontext, null, "", null);
            }
        } else {
            passwordView = new PayPasswordView(3, 1, mcontext, orderInfo, orderPrice, null);
        }
        passwordView.setOnPayListener(new OnPayListener() {

            @Override
            public void onSurePay(String password) {
                if (isBalancePay) {
                    balancePay(password);
                } else {
                    submitNextBuyInfo(password);
                }
            }

            @Override
            public void onCancelPay() {
                ActivityUtils.backgroundAlpha(mcontext, 0.5f);
                if (mDialogWidget != null) {
                    mDialogWidget.dismiss();
                }
                mDialogWidget = null;
            }
        });
        return passwordView.getView();
    }

    private void submitNextBuyInfo(String code) {
        ActionUtil actionUtil = new ActionUtil(mcontext);
        actionUtil.submitPayInfo(cardInfo.getCardNo(), orderInfo.getOrderNo(), code, cardInfo.getPayGate(), cardInfo.getSubGate());
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {

                if (model == null) {
                    UIHelper.showToast(mcontext, mcontext.getString(R.string.rank_fail));
                    return;
                }
                if (model.getErrorMsg() != null) {
                    if (model.getErrorCode().equals(Strs.EXTRUSION_SIGN_IN)) {
                        ActivityUtils.forceQuit(mcontext, mcontext.getString(R.string.crowding_in_tips_txt));
                    } else {
                        UIHelper.showToast(mcontext, model.getErrorMsg());
                        passwordView.clearUi();
                    }
                } else {
                    if ("true".equals(model.getStatus())) {
                        checkOrderStatus();
                    } else {
                        passwordView.clearUi();
                        UIHelper.showToast(mcontext, model.getInfo());
                    }
                }
            }
        });
    }

    protected void checkOrderStatus() {
        ActionUtil actionUtil = new ActionUtil(mcontext);
        actionUtil.searchOrderState(orderInfo.getOrderNo(), cardInfo.getPayGate(), cardInfo.getSubGate());
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                if (model == null) {
                    UIHelper.showToast(mcontext, mcontext.getString(R.string.rank_fail));
                    return;
                }
                if (model.getErrorMsg() != null) {
                    if (model.getErrorCode().equals(Strs.EXTRUSION_SIGN_IN)) {
                        ActivityUtils.forceQuit(mcontext, mcontext.getString(R.string.crowding_in_tips_txt));
                    } else {
                        UIHelper.showToast(mcontext, model.getErrorMsg());
                    }
                } else {
                    if ("true".equals(model.getStatus())) {
                        passwordView.showSuccessUi();
                        new Thread(new Runnable() {
                            public void run() {
                                try {
                                    Thread.sleep(1000);
                                    if (mType.equals("1")) {
                                        String type = null;
                                        if ("HQ".equals(orderInfo.getOrderNo().substring(0, 2))) {
                                            type = "buyCurrentSuccess";
                                        } else {
                                            type = "buyRegularSuccess";
                                        }
                                        ActivityUtils.gotoTransRecord(mcontext, type);
                                    } else if (mType.equals("2")) {
                                        skipToWallet();
                                        if (mcontext != null && mcontext instanceof RechargeFStebActivity) {
                                            mcontext.finish();
                                        }
                                    } else if (mType.equals("3")) {
                                        ActivityUtils.gotoTransRecord(mcontext, "pickSuccess");
                                    } else if (mType.equals("4")) {
                                        ActivityUtils.gotoTransRecord(mcontext, "exchangeSuccess");
                                    }
                                    if (mDialogWidget != null) {
                                        mDialogWidget.dismiss();
                                    }
                                    mDialogWidget = null;
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }).start();
                    } else {
                        time = time + 1;
                        if (time == 2) {
                            new Thread(new Runnable() {
                                public void run() {
                                    try {
                                        Thread.sleep(2000);
                                        handle.sendEmptyMessage(0);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }).start();
                        } else {
                            if (mDialogWidget != null) {
                                mDialogWidget.dismiss();
                            }
                            mDialogWidget = null;
                            if ("2".equals(mType)) {
                                new MyAlertDialog(mcontext).builder().setMsg("暂时无法获取付款结果，请稍后转至资金明细页面查看。")
                                        .setCancelable(false).setPositiveButton("确定", true, new OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        ActivityUtils.skipToMain(mcontext, "orderFail");
                                    }
                                }).show();
                            } else {
                                new MyAlertDialog(mcontext).builder().setMsg("服务器繁忙，暂时无法获取付款结果，请稍后转至投资记录页面查看结果。")
                                        .setCancelable(false).setPositiveButton("确定", true, new OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        ActivityUtils.skipToMain(mcontext, "orderFail");
                                    }
                                }).show();
                            }

                        }
                    }
                }
            }
        });
    }

    private void balancePay(String password) {
        ActionUtil actionUtil = new ActionUtil(mcontext);
        actionUtil.submitBalancePayInfo(password, orderPrice, orderInfo.getOrderNo());
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                if (model == null) {
                    UIHelper.showToast(mcontext, mcontext.getString(R.string.rank_fail));
                    return;
                }
                if (model.getErrorMsg() != null) {
                    passwordView.clearUi();
                    UIHelper.showToast(mcontext, model.getErrorMsg());

                } else {
                    if ("true".equals(model.getStatus())) {
                        passwordView.showSuccessUi();
                        new Thread(new Runnable() {
                            public void run() {
                                try {
                                    Thread.sleep(1000);
                                    if (mType.equals("1")) {
                                        String type = null;
                                        if ("HQ".equals(orderInfo.getOrderNo().substring(0, 2))) {
                                            type = "buyCurrentSuccess";
                                        } else {
                                            type = "buyRegularSuccess";
                                        }
                                        ActivityUtils.gotoTransRecord(mcontext, type);
                                    } else if (mType.equals("3")) {
                                        ActivityUtils.gotoTransRecord(mcontext, "pickSuccess");
                                    } else if (mType.equals("4")) {
                                        ActivityUtils.gotoTransRecord(mcontext, "exchangeSuccess");
                                    }
                                    if (mDialogWidget != null) {
                                        mDialogWidget.dismiss();
                                    }
                                    mDialogWidget = null;

                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }).start();
                    } else {
                        passwordView.clearUi();
                        passwordView.setErrorTip(model.getInfo());
                    }
                }
            }
        });
    }

    private void skipToWallet() {
        Intent intent = new Intent();
        intent.setClass(mcontext, MyWalletActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        mcontext.startActivity(intent);
    }
}
